package com.tarena.demo.luban.all.main.service.impl;

import com.tarena.demo.luban.all.main.mapper.OrderMapper;
import com.tarena.demo.luban.all.main.service.OrderService;
import com.tarena.demo.luban.protocol.order.dos.OrderDO;
import com.tarena.demo.luban.protocol.order.param.OrderAddParam;
import com.tarena.luban.demo.cart.api.CartRpcApi;
import com.tarena.luban.demo.stock.api.StockApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired(required = false)
    private CartRpcApi cartRpcApi;
    @Autowired(required = false)
    private StockApi stockApi;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

//    @SentinelResource(value = "orderAddParam",blockHandler = "blockHandle",
//            blockHandlerClass = AddOrderServiceBlockHandler.class,fallback = "fallback")
    @Override public void addOrder(OrderAddParam param) {
        // 减库存
        String orderSn = param.getOrderSn();
        Integer count = orderMapper.countOrderByOrderSn(orderSn);
        if(count>0){
            log.info("当前订单已经不存在了"+orderSn);
            return;
        }
        stockApi.StockDelete(param.getCount(), param.getProductCode(), param.getOrderSn());
        //增订单
        OrderDO orderDO=new OrderDO();
        BeanUtils.copyProperties(param,orderDO);
        orderMapper.insertOrder(orderDO);
        //删除购物车

        Message message = MessageBuilder.withPayload(param).build();
        rocketMQTemplate.asyncSend("cart-delete-topic", message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {

            }

            @Override
            public void onException(Throwable throwable) {

            }
        });
//        cartRpcApi.cartDelete(param.getUserId(), param.getProductCode());
    }

    public void fallback(OrderAddParam param, Throwable e){
        System.out.println("原方法出现异常");
    }
}
